#include "List.h"

List::List()
{
	phead = NULL;
	sophantu = 0;
}


List::~List()
{
	/*Node *p = phead;
	while (p != NULL)
	{
		Node *q = p->next;
		delete p;
		p = q;
	}*/
}

Node * List::CreateNode(Donthuc dt)
{
	Node *node = new Node;
	node->donthuc = dt;
	node->next = NULL;

	return node;
}

void List::AddHead(Donthuc dt)
{
	Node *p = CreateNode(dt);
	if (phead == NULL)
		phead = p;
	else
	{
		p->next = phead;
		phead = p;
	}

	++sophantu;
}

void List::AddTail(Donthuc dt)
{
	Node *p = CreateNode(dt);
	if (phead == NULL)
		phead = p;
	else
	{
		Node *q = phead;
		while (q->next != NULL) //tim node cuoi cung
			q = q->next;
		q->next = p;
	}
	++sophantu;
}

///sumary
///add mot don thuc vao vi tri bat ki
///<parameter>i - vi tri can them</parameter>
///<parameter>dt - don thuc can them</parameter>
void List::AddPosition(int i, Donthuc dt)
{
	if (i < 0) return;

	int currIndex = 1;
	Node* currNode = phead;
	while (currNode && i > currIndex) {
		currNode = currNode->next;
		currIndex++;
	}
	if (i > 0 && currNode == NULL) return;

	Node* newNode = new	Node;
	newNode = CreateNode(dt);
	if (i == 0) {
		AddHead(dt);
	}
	else {
		newNode->next = currNode->next;
		currNode->next = newNode;
		++sophantu;
	}
}

int List::DeletePosition(int i)
{
	int currposition = 1;
	Node *p = phead;
	if (i < 0)
		return -1;
	if (phead == NULL)
		return 1;
	if (i == 0)
	{
		--sophantu;
		phead = phead->next;
		return 1;
	}
	while (p != NULL && currposition != i) //tim vi tri truoc phan tu muon xoa
	{
		p = p->next;
		++currposition;
	}

	if (i == currposition)
	{
		if (p->next == NULL) //neu phan tu muon xoa la NULL
			return 1;
		else
		{
			Node *q = p->next; // q la Node muon xoa
			p->next = q->next;
			delete q;
			--sophantu;
		}
	}
	else
		return -1;
	return 1;
}

Donthuc & List::GetValue(int i)
{
	Donthuc a;
	if (i < 0)
		return a;

	int pos = 0;
	Node *p = phead;
	while (pos != i && p != NULL)
	{
		++pos;
		p = p->next;
	}

	if (pos == i && p != NULL)
		return p->donthuc;

	return a;

}

void List::Add(Donthuc dt)
{
	AddTail(dt);
}


bool List::SetValue(int i, Donthuc dt)
{
	if (i < 0)
		return false;
	int pos = 0;
	Node *p = phead;
	while (pos != i && p != NULL)
	{
		++pos;
		p = p->next;
	}

	if (pos == i)
	{
		p->donthuc = dt;
	}
	else
		return false;
	return true;
}

